# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import threading
from utils import data_queue

d_M_y_h_m_s = '%d%m%y%H%M%S'  # 小写y，是舍弃公元纪年21，大写Y是公元纪年2021
Y_M_D_H_M_S = '%Y-%m-%d %H:%M:%S'  # 年月天


class Loopthread(threading.Thread):
    def __init__(self, mqttnode):
        threading.Thread.__init__(self)
        self.mqtt_node = mqttnode

    def run(self):
        self.mqtt_node.client.loop_forever()


class MqttClientNode(object):
    def __init__(self, vehicleid, host, port):
        self.pbt = PubThread(self)
        self.__host = host
        self.__port = port
        self.client_id = vehicleid
        self.client = mqtt.Client(self.client_id)
        self.client.username_pw_set("admin", "123")
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_subscribe = self.on_subscribe
        self.client.on_disconnect = self.on_disconnect
        self.queue = data_queue.DataQueue()

    def __del__(self):
        pass

    def loop_forver(self):
        lp = Loopthread(self)
        lp.start()

    def connect_host(self):
        try:
            self.client.connect(self.__host, self.__port, 1800)  # 60s
        except Exception as e:
            print(e)

    def subscribe(self, topic):
        try:
            self.client.subscribe(topic)
        except Exception as e:
            print(e)

    def on_connect(self, client, userdata, flags, rc):
        print("%s Connected with result code " % self.client_id)

    def on_subscribe(self, client, userdata, mid, granted_qos):
        print("On Subscribed: qos = %d" % granted_qos)

    def on_disconnect(self, client, userdata, rc):
        if rc != 0:
            print("Unexpected disconnection %s" % rc)

    def on_message(self, client, userdata, msg):
        # print("主题:" + msg.topic + " 消息:" + str(msg.payload, encoding='utf-8'))
        print("节点:%s 接收数据，总共:%d字节" % (self.client_id, len(str(msg.payload, encoding='utf-8'))))

    def active_pubish(self):
        self.pbt.start()

    def add(self, mq_meta):
        self.__queue.append(mq_meta)


class PubThread(threading.Thread):
    def __init__(self, mqttnode):
        threading.Thread.__init__(self)
        self.mqtt_node = mqttnode

    def run(self):
        while self.mqtt_node.queue.len() > 0:
            data = self.mqtt_node.queue.pop()
            self.mqtt_node.client.publish(data.get_topic(), payload=data.get_payload(), qos=0)  # 发送消息
            print(data)


if __name__ == '__main__':
    mq_node = MqttClientNode("", "47.111.163.13", 1883)
    mq_node.connect_host()
    mq_node.active_pubish()
    mq_node.loop_forver()
